import React, { useState } from 'react';
import {
  Box,
  Container,
  Typography,
  Grid,
  Card,
  CardContent,
  CardMedia,
  CardActions,
  Button,
  TextField,
  InputAdornment,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Pagination,
  Chip,
  IconButton,
  useTheme,
  SelectChangeEvent
} from '@mui/material';
import {
  Search as SearchIcon,
  Edit as EditIcon,
  Delete as DeleteIcon
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../../store';
import { useGetArticlesQuery, useDeleteArticleMutation } from '../../store/services/articles';
import { Article } from '../../types/article';
import Loading from '../../components/common/Loading';

const ArticleList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  const { user } = useSelector((state: RootState) => state.auth);
  
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState<string>('');
  const [sort, setSort] = useState('createdAt,desc');
  
  const { data: response, isLoading, error } = useGetArticlesQuery({
    page: page - 1,
    size: 12,
    search,
    categoryId: category ? parseInt(category) : undefined,
    sort
  });

  const articles = response?.data.content || [];
  const totalPages = response?.data.totalPages || 0;

  const [deleteArticle] = useDeleteArticleMutation();

  const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(event.target.value);
    setPage(1);
  };

  const handleCategoryChange = (event: SelectChangeEvent) => {
    setCategory(event.target.value);
    setPage(1);
  };

  const handleSortChange = (event: SelectChangeEvent) => {
    setSort(event.target.value);
    setPage(1);
  };

  const handleDelete = async (id: number) => {
    if (window.confirm(t('article.delete.confirm'))) {
      try {
        await deleteArticle(id).unwrap();
      } catch (err) {
        console.error('Delete article failed:', err);
      }
    }
  };

  if (isLoading) {
    return <Loading />;
  }

  if (error) {
    return (
      <Box sx={{ p: 3, textAlign: 'center' }}>
        <Typography color="error">
          {t('common.error')}
        </Typography>
      </Box>
    );
  }

  return (
    <Container maxWidth="lg">
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          {t('article.list.title')}
        </Typography>

        {/* 工具栏 */}
        <Grid container spacing={2} sx={{ mb: 4 }}>
          <Grid item xs={12} md={4}>
            <TextField
              fullWidth
              placeholder={t('article.list.search')}
              value={search}
              onChange={handleSearchChange}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={3}>
            <FormControl fullWidth>
              <InputLabel>{t('article.list.category')}</InputLabel>
              <Select
                value={category}
                label={t('article.list.category')}
                onChange={handleCategoryChange}
              >
                <MenuItem value="">{t('article.list.allCategories')}</MenuItem>
                {/* TODO: 添加分类选项 */}
              </Select>
            </FormControl>
          </Grid>

          <Grid item xs={12} md={3}>
            <FormControl fullWidth>
              <InputLabel>{t('article.list.sort')}</InputLabel>
              <Select
                value={sort}
                label={t('article.list.sort')}
                onChange={handleSortChange}
              >
                <MenuItem value="createdAt,desc">{t('article.list.newest')}</MenuItem>
                <MenuItem value="createdAt,asc">{t('article.list.oldest')}</MenuItem>
                <MenuItem value="viewCount,desc">{t('article.list.mostViewed')}</MenuItem>
                <MenuItem value="likeCount,desc">{t('article.list.mostLiked')}</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          <Grid item xs={12} md={2}>
            <Button
              fullWidth
              variant="contained"
              color="primary"
              onClick={() => navigate('/articles/new')}
            >
              {t('article.create.title')}
            </Button>
          </Grid>
        </Grid>

        {/* 文章列表 */}
        <Grid container spacing={3}>
          {articles.map((article: Article) => (
            <Grid item key={article.id} xs={12} sm={6} md={4}>
              <Card
                sx={{
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  transition: 'transform 0.2s',
                  '&:hover': {
                    transform: 'translateY(-4px)',
                    boxShadow: theme.shadows[4]
                  }
                }}
              >
                <CardMedia
                  component="img"
                  height="200"
                  image={article.cover || '/placeholder.jpg'}
                  alt={article.title}
                  sx={{ objectFit: 'cover' }}
                />
                <CardContent sx={{ flexGrow: 1 }}>
                  <Typography gutterBottom variant="h6" component="h2" noWrap>
                    {article.title}
                  </Typography>
                  <Typography
                    variant="body2"
                    color="text.secondary"
                    sx={{
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      display: '-webkit-box',
                      WebkitLineClamp: 3,
                      WebkitBoxOrient: 'vertical',
                      mb: 2
                    }}
                  >
                    {article.summary}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap', mb: 2 }}>
                    <Chip
                      label={article.category.name}
                      size="small"
                      color="primary"
                      onClick={() => setCategory(article.category.id.toString())}
                    />
                    {article.tags.slice(0, 2).map((tag) => (
                      <Chip
                        key={tag.id}
                        label={tag.name}
                        size="small"
                        variant="outlined"
                      />
                    ))}
                  </Box>
                  <Typography variant="caption" color="text.secondary" component="div">
                    {t('article.detail.author')}: {article.author.username}
                  </Typography>
                  <Typography variant="caption" color="text.secondary" component="div">
                    {new Date(article.createdAt).toLocaleDateString()}
                  </Typography>
                </CardContent>
                <CardActions sx={{ justifyContent: 'space-between', px: 2, pb: 2 }}>
                  <Button
                    size="small"
                    onClick={() => navigate(`/articles/${article.id}`)}
                  >
                    {t('common.more')}
                  </Button>
                  {(user?.role === 'ADMIN' || user?.id === article.author.id) && (
                    <Box>
                      <IconButton
                        size="small"
                        onClick={() => navigate(`/articles/edit/${article.id}`)}
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                      <IconButton
                        size="small"
                        color="error"
                        onClick={() => handleDelete(article.id)}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  )}
                </CardActions>
              </Card>
            </Grid>
          ))}
        </Grid>

        {/* 分页 */}
        {totalPages > 1 && (
          <Box sx={{ mt: 4, display: 'flex', justifyContent: 'center' }}>
            <Pagination
              count={totalPages}
              page={page}
              onChange={(_, value) => setPage(value)}
              color="primary"
            />
          </Box>
        )}
      </Box>
    </Container>
  );
};

export default ArticleList; 